<template>
  <el-form ref="formRef" :model="form" :rules="rules" label-width="auto" style="max-width: 1000px">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="BOM编号" prop="domCode">
          <el-input v-model="form.domCode" :disabled="form.isSystemCode" />
          <el-checkbox v-model="form.isSystemCode" @change="handleSystemCodeChange">系统编号</el-checkbox>
        </el-form-item>
        <el-form-item label="默认BOM">
          <el-checkbox v-model="form.domIsDel" />
        </el-form-item>
        <el-form-item label="成品类型" prop="domType">
          <el-select v-model="form.domType" placeholder="请选择成品类型">
            <el-option label="电子产品" value="electronic"></el-option>
            <el-option label="机械零件" value="mechanical"></el-option>
            <el-option label="化工产品" value="chemical"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="日产量" prop="yieId">
          <el-input v-model.number="form.yieId" placeholder="请输入日产量" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="BOM主题" prop="domTopic">
          <el-input v-model="form.domTopic" placeholder="请输入BOM主题" />
        </el-form-item>
        <el-form-item label="版本" prop="domVersion">
          <el-input v-model="form.domVersion" placeholder="请输入版本" />
        </el-form-item>
        <el-form-item label="成品名称" prop="domName">
          <el-input v-model="form.domName" placeholder="请选择物品" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item>
      <el-button type="primary" @click="submitBomForm" :disabled="isBasicInfoSubmitted">提交</el-button>
      <el-button @click="resetForm">取消</el-button>
    </el-form-item>
    <el-divider />
    <div class="bom-accessories">
      <div style="margin-bottom: 10px;">
        <el-button type="primary" @click="addAccessory" :disabled="!isBasicInfoValid">新增行</el-button>
        <el-button type="danger" @click="removeAccessory" :disabled="!selectedAccessories.length">删除行</el-button>
      </div>
      <el-table :data="accessories" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="94"></el-table-column>
        <el-table-column label="序号" type="index" width="105"></el-table-column>
        <el-table-column label="物品编号" width="182">
          <template #default="scope">
            <el-input v-model="scope.row.code" size="default" placeholder="请输入物品编号"
              :disabled="scope.row.isQueried && !scope.row.isEditing" />
          </template>
        </el-table-column>
        <el-table-column label="物品名称" width="182">
          <template #default="scope">
            <el-input v-model="scope.row.name" size="default" placeholder="请输入物品名称"
              :disabled="scope.row.isQueried && !scope.row.isEditing" />
          </template>
        </el-table-column>
        <el-table-column label="规格型号" width="215">
          <template #default="scope">
            <el-input v-model="scope.row.model" size="default" placeholder="请输入规格型号"
              :disabled="scope.row.isQueried && !scope.row.isEditing" />
          </template>
        </el-table-column>
        <el-table-column label="单位" width="116">
          <template #default="scope">
            <el-input v-model="scope.row.unit" size="default" placeholder="单位"
              :disabled="scope.row.isQueried && !scope.row.isEditing" />
          </template>
        </el-table-column>
        <el-table-column label="品牌" width="160">
          <template #default="scope">
            <el-input v-model="scope.row.brand" size="default" placeholder="请输入品牌"
              :disabled="scope.row.isQueried && !scope.row.isEditing" />
          </template>
        </el-table-column>
        <el-table-column label="配件数量" width="182">
          <template #default="scope">
            <el-input v-model="scope.row.quantity" size="default" placeholder="请输入数量"
              :disabled="scope.row.isQueried && !scope.row.isEditing" />
          </template>
        </el-table-column>
        <el-table-column label="损耗率" width="182">
          <template #default="scope">
            <el-input v-model="scope.row.lossRate" size="default" placeholder="请输入损耗率"
              :disabled="scope.row.isQueried" />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作列" min-width="120">
          <template #default="scope">
            <template v-if="scope.row.isQueried">
              <template v-if="scope.row.isEditing">
                <el-button link type="success" size="small" @click="handleSave(scope.row)">
                  保存
                </el-button>
                <el-button link type="info" size="small" @click="handleCancel(scope.row)">
                  取消
                </el-button>
              </template>
              <template v-else>
                <el-button link type="primary" size="small" @click="handleEdit(scope.row)">
                  修改
                </el-button>
                <el-button link type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 20px; text-align: center;">
        <el-button type="success" @click="submitAccessories" :disabled="!accessories.length">提交BOM配件</el-button>
      </div>
    </div>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref, watch, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { read, write } from '@/axios/axiosHelper'

// BOM表单相关
const formRef = ref<FormInstance | null>(null);
const form = reactive({
  domCode: '',
  isSystemCode: false,
  domIsDel: false,
  domTopic: '',
  domType: '',
  domVersion: '',
  domName: '',
  yieId: 0,
  remark: ''
});

onMounted(() => {
  getDOMDetails();
})

const getDOMDetailsList = ref<any[]>([]);
const getDOMDetails = () => {
  read.get("/f-read/api/DOM/GetDOMDetails",
    {
      params: {
        domId: submittedData.value
      }
    }
  )
    .then(res => {
      console.log("获取DOMDetails数据：", res.data.data);
      getDOMDetailsList.value = res.data.data;
    })
    .catch(error => {
      console.log(error);
    })
}

// 监听getDOMDetailsList变化，当有数据时更新配件表格
watch(getDOMDetailsList, (newValue) => {
  if (newValue && newValue.length > 0 && submittedData.value) {
    accessories.value = newValue.map(item => ({
      domId: submittedData.value,
      domDetailsId: item.domDetailsId,
      code: item.code || '',
      name: item.name || '',
      model: item.model || '',
      unit: item.unit || '',
      brand: item.brand || '',
      quantity: item.quantity || '',
      lossRate: item.lossRate || '',
      isQueried: true, // 标记为查询出的配件
      isEditing: false // 初始化为非编辑状态
    }));
  }
}, { deep: true });

const rules = reactive({
  domCode: [
    { required: true, message: 'BOM编号不能为空', trigger: 'blur' },
    { min: 5, message: '编号长度不能少于5个字符', trigger: 'blur' }
  ],
  domType: [
    { required: true, message: '请选择成品类型', trigger: 'change' }
  ],
  yieId: [
    { required: true, message: '请输入日产量', trigger: 'blur' },
    { type: 'number', message: '日产量必须为数字', trigger: 'blur' }
  ],
  domTopic: [
    { required: true, message: 'BOM主题不能为空', trigger: 'blur' }
  ],
  domVersion: [
    { required: true, message: '版本不能为空', trigger: 'blur' }
  ],
  domName: [
    { required: true, message: '成品名称不能为空', trigger: 'blur' }
  ]
});

// 配件数据
interface Accessory {
  domId: number;
  domDetailsId?: number;
  code: string;
  name: string;
  model: string;
  unit: string;
  brand: string;
  quantity: string;
  lossRate: string;
  isQueried?: boolean;
  isEditing?: boolean;
}

const accessories = ref<Accessory[]>([]);
const selectedAccessories = ref<Accessory[]>([]);

// 选择行
const handleSelectionChange = (val: Accessory[]) => {
  selectedAccessories.value = val;
}

// 检查基本信息是否有效
const isBasicInfoValid = ref(false);

// 基本信息是否已提交
const isBasicInfoSubmitted = ref(false);
// 存储提交后返回的数据
const submittedData = ref<any>(null);

// 监听表单变化
watch(() => form, (newForm) => {
  // 检查必填字段是否都已填写
  isBasicInfoValid.value = !!(
    newForm.domCode &&
    newForm.domType &&
    newForm.domTopic &&
    newForm.domVersion &&
    newForm.domName &&
    newForm.yieId > 0
  );
}, { deep: true });

// 添加配件
const addAccessory = () => {
  if (!isBasicInfoValid.value) {
    ElMessage.warning('请先完善基本信息');
    return;
  }
  if (!submittedData.value) {
    ElMessage.warning('请先提交基本信息');
    return;
  }
  accessories.value.push({
    domId: submittedData.value,
    domDetailsId: undefined,
    code: '', name: '', model: '', unit: '', brand: '', quantity: '', lossRate: '', isQueried: false, isEditing: false
  });
};

// 移除配件
const removeAccessory = () => {
  // 检查选中的行是否包含查询出的数据
  const hasQueriedData = selectedAccessories.value.some(item => item.isQueried);

  if (hasQueriedData) {
    ElMessage.warning('当前不能删除，所选行有数据');
    return;
  }

  accessories.value = accessories.value.filter(item => !selectedAccessories.value.includes(item));
  selectedAccessories.value = [];
}

// 生成BOM编号
const generatedomCode = () => {
  const timestamp = new Date().getTime().toString().slice(-6);
  const randomStr = Math.random().toString(36).slice(2, 5).toUpperCase();

  let prefix = 'BOM';
  if (form.domType === 'electronic') prefix = 'ELC';
  if (form.domType === 'mechanical') prefix = 'MEC';
  if (form.domType === 'chemical') prefix = 'CHE';

  return `${prefix}-${timestamp}-${randomStr}`;
};

// 处理系统编号勾选变化
const handleSystemCodeChange = (checked: boolean) => {
  if (checked) {
    // 检查是否已选择成品类型
    if (!form.domType) {
      ElMessage.warning('请先选择成品类型再生成系统编号');
      form.isSystemCode = false;
      return;
    }

    form.domCode = generatedomCode();
  } else {
    form.domCode = '';
  }
};

// 监听成品类型变化，更新编号前缀
watch(() => form.domType, (newVal) => {
  if (form.isSystemCode && form.domCode) {
    // 如果已生成编号且修改了类型，重新生成
    form.domCode = generatedomCode();
  }
});

// 提交BOM表单
const submitBomForm = () => {
  // 系统编号模式下自动生成
  if (form.isSystemCode && !form.domCode) {
    form.domCode = generatedomCode();
  }

  if (formRef.value) {
    formRef.value.validate((valid: boolean) => {
      if (valid) {
        const payload = {
          ...form,
          accessories: accessories.value
        }
        write.post('/f-write/api/DOM/AddDOM', payload)
          .then(res => {
            if (res.data.code === 200) {
              ElMessage.success(res.data.msg);
              // 保存返回的数据
              submittedData.value = res.data.data;
              console.log('提交成功，返回数据：', submittedData.value);
              // 禁用提交按钮
              isBasicInfoSubmitted.value = true;
              // 清空配件列表，因为基本信息已更新
              accessories.value = [];
              selectedAccessories.value = [];
            } else {
              ElMessage.error(res.data.msg);
            }
          })
          .catch(error => {
            ElMessage.error('提交失败:' + error.message);
            console.error(error);
          });
      } else {
        ElMessage.warning('请完善表单信息');
      }
    });
  }
};

// 重置BOM表单
const resetForm = () => {
  // 重置基本信息提交状态
  isBasicInfoSubmitted.value = false;
  // 清空返回数据
  submittedData.value = null;
  // 重置表单数据
  for (const key in form) {
    if (form.hasOwnProperty(key)) {
      if (typeof form[key] === 'boolean') form[key] = false;
      else if (typeof form[key] === 'string') form[key] = '';
      else if (typeof form[key] === 'number') form[key] = 0;
    }
  }
  // 清空配件列表
  accessories.value = [];
  selectedAccessories.value = [];
};

// 提交BOM配件
const submitAccessories = async () => {
  if (!isBasicInfoValid.value) {
    ElMessage.warning('请先完善基本信息');
    return;
  }

  if (!accessories.value.length) {
    ElMessage.warning('请先添加配件信息');
    return;
  }

  // 验证配件数据
  const invalidAccessories = accessories.value.filter(item =>
    !item.code || !item.name || !item.model || !item.unit || !item.brand || !item.quantity
  );

  if (invalidAccessories.length > 0) {
    ElMessage.warning('请完善所有配件信息');
    return;
  }

  // 构建批量提交的数据
  const batchData = accessories.value.map(item => ({
    domId: submittedData.value,
    domDetailsId: item.domDetailsId,
    code: item.code,
    name: item.name,
    model: item.model,
    unit: item.unit,
    brand: item.brand,
    quantity: item.quantity,
    lossRate: item.lossRate
  }));

  console.log("配件数据：", batchData);

  try {
    // 循环添加每个配件
    for (let i = 0; i < batchData.length; i++) {
      const item = batchData[i];
      console.log(`正在添加第 ${i + 1}/${batchData.length} 个配件:`, item);

      const res = await write.post("/f-write/api/DOMDetails/AddDOMDetails", item);

      if (res.data.code === 200) {
        console.log(`第 ${i + 1} 个配件添加成功`);
      } else {
        throw new Error(`第 ${i + 1} 个配件添加失败: ${res.data.msg}`);
      }
    }

    // 所有配件添加成功
    ElMessage.success('所有配件添加成功');
    // 清空配件列表
    accessories.value = [];
    selectedAccessories.value = [];

    // 重新获取配件列表数据
    await getDOMDetails();

  } catch (error: any) {
    ElMessage.error('添加失败: ' + error.message);
    console.error('添加失败:', error);
  }
};

// 修改处理函数
const handleEdit = (row: Accessory) => {
  // 将当前行设置为编辑状态
  row.isEditing = true;
  // 临时禁用其他行的编辑按钮
  accessories.value.forEach(item => {
    if (item !== row) {
      item.isEditing = false;
    }
  });
};

// 保存处理函数
const handleSave = async (row: Accessory) => {
  try {
    const res = await write.post("/f-write/api/DOMDetails/UpdateDOMDetails", {
      domDetailsId: row.domDetailsId,
      domId: row.domId,
      code: row.code,
      name: row.name,
      model: row.model,
      unit: row.unit,
      brand: row.brand,
      quantity: row.quantity,
      lossRate: row.lossRate
    });

    if (res.data.code === 200) {
      ElMessage.success('保存成功');
      row.isEditing = false;
      // 重新获取配件列表
      await getDOMDetails();
    } else {
      ElMessage.error(res.data.msg || '保存失败');
    }
  } catch (error: any) {
    ElMessage.error('保存失败: ' + error.message);
  }
};

// 取消处理函数
const handleCancel = async (row: Accessory) => {
  // 取消编辑，重新获取数据
  await getDOMDetails();
  row.isEditing = false;
};

// 删除处理函数
const handleDelete = (row: Accessory) => {
  ElMessageBox.confirm(
    '确定要删除这个配件吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        // 调用删除API
        const res = await write.post(`/f-write/api/DOMDetails/DeleteDOMDetails`, {
          domDetailsId: row.domDetailsId
        });
        if (res.data.code === 200) {
          ElMessage.success('删除成功');
          // 重新获取配件列表
          getDOMDetails();
        } else {
          ElMessage.error(res.data.msg || '删除失败');
        }
      } catch (error: any) {
        ElMessage.error('删除失败: ' + error.message);
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除');
    });
};
</script>

<style scoped>
.bom-accessories {
  margin-top: 20px;
}
</style>